package com.kly.sc.api.application.controller.sms;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.dto.MsgResultDto;
import com.kly.dto.SmsBackRequestDTO;
import com.kly.dto.SmsConfigRequestDTO;
import com.kly.dto.SmsRequestDTO;
import com.kly.sc.api.application.annos.SignIgnore;
import com.kly.sc.api.application.constant.ApiRedisKeys;
import com.kly.sc.api.application.enums.ApiResultStatus;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.utils.BaseUtils;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.service.SMSService;
import com.kly.user.enums.RememberTime;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@RestController
@RequestMapping("api/sms")
public class SMSController {

    private static final Log logger = LogFactory.getLog(SMSController.class);

    @Autowired(required = false)
    SMSService smsService;

    @Autowired
    RedisClient redisClient;

    private static long ONE = 1;

    @ApiOperation("发送短信")
    @ResponseBody
    @RequestMapping(value = "/sendSMS",method = RequestMethod.POST)
    @SignIgnore
    public Response sendSMS(@Valid @RequestBody SmsRequestDTO smsRequest, BindingResult results) {
        final String appCode = RequestLocalInfo.getRequestBasicInfo().getAppCode();
        //传了白名单直接返回，白名单走谷歌短信
        String whitePhone = redisClient.hGet(ApiRedisKeys.WHITE_USER.getValue(), smsRequest.getPhone());
        if(StringUtils.isNotEmpty(whitePhone) ){
            return Response.ok();
        }


        if (results.hasErrors()) {
            return Response.error(ApiResultStatus.PHONE_NUMBER_IS_EMPTY);
        }
        String phone = smsRequest.getPhone();
        Long number = redisClient.getNumber(ApiRedisKeys.PHONE_VERIFICATION_CODE_NUMBER.getValue(),
                phone);
        if (number != null && number >= ApiRedisKeys.PHONE_VERIFICATION_CODE_NUMBER.getKey()) {
            return Response.error(ApiResultStatus.PHONE_VERIFICATION_CODE_LIMIT);
        }
        MsgResultDto msgResultDto = smsService.sendSMS(smsRequest);
        if (StringUtils.isNotEmpty(msgResultDto.getContent())) {
            redisClient.set(ApiRedisKeys.PHONE_VERIFICATION_CODE.getValue(), msgResultDto.getContent(), RememberTime.TNE_MINUTES.getTime(), appCode, phone);
            if (number != null) {
                redisClient.incrBy(ApiRedisKeys.PHONE_VERIFICATION_CODE_NUMBER.getValue(), ONE, phone);
            } else {
                redisClient.setNumber(ApiRedisKeys.PHONE_VERIFICATION_CODE.getValue(), ONE, BaseUtils.getSeconds((int) ONE), appCode, phone);
            }
            return Response.ok(msgResultDto);
        }
        return Response.error(ApiResultStatus.MESSAGE_FAILED_TO_SEND);
    }



    /**
     * 短信第三方回调接口
     * @param requestDTO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/smsCallBack",method = RequestMethod.POST)
    @SignIgnore
    public Response smsCallBack(@Valid @RequestBody SmsBackRequestDTO requestDTO){
        logger.info("收到颂量回调:"+ JSONObject.toJSONString(requestDTO));
        return Response.ok(RpcUtils.getResult(smsService.smsCallBack(requestDTO)));
    }


    /**
     * 短信调用配置 1谷歌短信 2颂量短信
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/smsConfig",method = RequestMethod.GET)
    @SignIgnore
    public Response smsConfig(){
        return Response.ok(redisClient.getNumber(ApiRedisKeys.SMS_PROVIDER.getValue()));
    }

    @ResponseBody
    @RequestMapping(value = "/updateSmsConfig",method = RequestMethod.POST)
    @SignIgnore
    public Response updateSmsConfig(@RequestBody SmsConfigRequestDTO smsConfigRequestDTO){

        return Response.ok(smsService.updateSmsConfig(smsConfigRequestDTO));
    }
}
